package com.muyu.danmo.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.danmo.domain.*;
import com.muyu.danmo.domain.dto.PersonAddDTO;
import com.muyu.danmo.domain.dto.PersonBaseInfoDTO;
import com.muyu.danmo.domain.dto.PersonPositionDTO;
import com.muyu.danmo.domain.dto.PositionInfoDTO;
import com.muyu.danmo.domain.enums.Condition;
import com.muyu.danmo.domain.enums.Positions;
import com.muyu.danmo.domain.enums.RealName;
import com.muyu.danmo.domain.mapstruct.PersonMapper;
import com.muyu.danmo.domain.vo.*;
import com.muyu.danmo.mapper.*;
import com.muyu.danmo.req.DanmoProvincesCities;
import com.muyu.danmo.service.*;
import com.muyu.danmo.util.GetPinyinInitial;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 个人信息新Service业务层处理
 *
 * @author yangle
 * @date 2024-12-10
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DanmoInformationCopy1ServiceImpl implements IDanmoInformationCopy1Service {
    @Autowired
    private DanmoInformationCopy1Mapper danmoInformationCopy1Mapper;

    @Autowired
    private IDanmoInformationFlagshipService danmoInformationFlagshipService;

    @Autowired
    private IDanmoCollectShellfishService danmoCollectShellfishService;

    @Autowired
    private IDanmoCollectMemberService danmoCollectMemberService;
    @Autowired
    private  DanmoPersonInfoService danmoPersonInfoService;

    private final DanmoPersonPositionService danmoPersonPositionService;

    private final PersonMapper personMapper;

    private final IDanmoAssociationTypeService iDanmoAssociationTypeService;

    private final IDanmoInformationContentService iDanmoInformationContentService;

    private final IDanmoInformationPhotosService iDanmoInformationPhotosService;

    private final IDanmoPersonalPicturesService iDanmoPersonalPicturesService;

@Autowired
private DanmoUserFollowsMapper danmoUserFollowsMapper;

    /**
     * 查询个人信息新
     *
     * @param danmoInformationCopy1 个人信息新主键
     * @return 个人信息新
     */
    @Autowired
    private DanmoUserVisitorsMapper danmoUserVisitorsMapper;
    @Override
    public Result selectDanmoInformationCopy1ById(DanmoInformationCopy1 danmoInformationCopy1) {

        PersonInfoVO danmoInformationCopy11 = danmoPersonInfoService.getPersonInfo(danmoInformationCopy1.getId());
        if(null == danmoInformationCopy11){
            throw new RuntimeException("未找到该用户");
        }


        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = null;
        if (loginUser != null) {
            userid = loginUser.getUserid();
        }

        // 名家推荐
        DanmoInformationFlagship danmoInformationFlagship = new DanmoInformationFlagship();
        danmoInformationFlagship.setInformationId(danmoInformationCopy11.getId());
        List<DanmoInformationFlagship> list = danmoInformationFlagshipService.selectDanmoInformationFlagshipList(danmoInformationFlagship);
        danmoInformationCopy11.setDanmoInformationFlagshipList(list);

        // 校验拾贝作品状态
        boolean b = danmoCollectMemberService.selectDanmoCollectMemberById(danmoInformationCopy11.getId());

        // 获取拾贝作品
        DanmoCollectShellfish danmoCollectShellfish = new DanmoCollectShellfish();
        danmoCollectShellfish.setInformationId(danmoInformationCopy11.getId());
        List<DanmoCollectShellfish> list1 = danmoCollectShellfishService.selectDanmoCollectShellfishList(danmoCollectShellfish);
        danmoInformationCopy11.setDanmoCollectShellfishList(list1);

        // 处理个人作品图片
        List<DanmoInformationContent> danmoInformationContentList = danmoInformationCopy11.getDanmoInformationContentList();
        if (danmoInformationContentList != null) {
            for (DanmoInformationContent danmoInformationContent : danmoInformationContentList) {
                String atlas = danmoInformationContent.getAtlas();

                // 如果 atlas 为 null 或空字符串，则跳过处理或赋予一个默认值
                if (atlas != null && !atlas.isEmpty()) {
                    String[] photoPaths = atlas.split(",");
                    List<DanmoAtlasList> atlasList = new ArrayList<>();

                    for (String photoPath : photoPaths) {
                        atlasList.add(new DanmoAtlasList(photoPath)); // 创建 DanmoAtlasList 对象并添加到列表中
                    }

                    danmoInformationContent.setAtlasList(atlasList); // 设置 DanmoAtlasList 对象的列表
                } else {
                    // 如果 atlas 为 null 或空字符串，可以选择处理逻辑，如清空或不做任何操作
                    danmoInformationContent.setAtlasList(new ArrayList<>());
                }
            }
        }

        // 如果 userid 为 null，跳过相关用户逻辑
        if (userid == null) {
            return update(danmoInformationCopy11);
        }

        // 关注信息
        DanmoUserFollowers danmoUserFollowers = danmoUserFollowsMapper.selectFollowById(userid, danmoInformationCopy1.getId());
        if (danmoUserFollowers != null) {
            danmoInformationCopy11.setIsFollow(String.valueOf(true));
        } else {
            danmoInformationCopy11.setIsFollow(String.valueOf(false));
        }

        // 新增关注
        DanmoUserVisitors danmoUserVisitors = new DanmoUserVisitors();
        danmoUserVisitors.setUserId(userid);
        danmoUserVisitors.setInformationId(danmoInformationCopy1.getId());
        String s = determineTable(danmoInformationCopy1.getAssociationType());
        danmoUserVisitors.setTableName(s);
        danmoUserVisitorsMapper.insertDanmoUserVisitors(danmoUserVisitors);

        if (danmoInformationCopy11.getUserId() != null) {
            if (danmoInformationCopy11.getUserId().equals(userid)) {
                danmoInformationCopy11.setIsShow("true");
            } else {
                danmoInformationCopy11.setIsShow("false");
            }
            if (danmoInformationCopy11 == null) {
                return Result.error("未找到相关信息");
            }
        }
        return update(danmoInformationCopy11);
    }



    public Result<DanmoInformationCopy1> update(DanmoInformationCopy1 danmoInformationCopy11) {
        DanmoUserVisitors danmoUserVisitors = new DanmoUserVisitors();
        danmoUserVisitors.setVisitTime(DateUtils.getNowDate());

        if (danmoInformationCopy11.getDanmoInformationBar() == null) {
            danmoInformationCopy11.setDanmoInformationBar(new DanmoInformationBar());
        }

        if (danmoInformationCopy11.getDanmoInformationPhotosList() == null) {
            danmoInformationCopy11.setDanmoInformationPhotosList(Collections.singletonList(new DanmoInformationPhotos()));
        }

        if (danmoInformationCopy11.getDanmoCollectShellfishList() == null) {
            danmoInformationCopy11.setDanmoCollectShellfishList(Collections.singletonList(new DanmoCollectShellfish()));
        }

        if (danmoInformationCopy11.getDanmoInformationMapTitleList() == null) {
            danmoInformationCopy11.setDanmoInformationMapTitleList(Collections.singletonList(new DanmoInformationMapTitle()));
        }

        if (danmoInformationCopy11.getDanmoInformationVideoList() == null) {
            danmoInformationCopy11.setDanmoInformationVideoList(Collections.singletonList(new DanmoInformationVideo()));
        }

        if (danmoInformationCopy11.getDanmoInformationContentList() == null) {
            danmoInformationCopy11.setDanmoInformationContentList(Collections.singletonList(new DanmoInformationContent()));
        }

        if (danmoInformationCopy11.getDanmoInformationVideoList() == null) {
            danmoInformationCopy11.setDanmoInformationVideoList(Collections.singletonList(new DanmoInformationVideo()));
        }

        if (danmoInformationCopy11.getDanmoInformationFlagshipList() == null) {
            danmoInformationCopy11.setDanmoInformationFlagshipList(Collections.singletonList(new DanmoInformationFlagship()));
        }

        return Result.success(danmoInformationCopy11);
    }



    public Result<PersonInfoVO> update(PersonInfoVO danmoInformationCopy11) {
        DanmoUserVisitors danmoUserVisitors = new DanmoUserVisitors();
        danmoUserVisitors.setVisitTime(DateUtils.getNowDate());

        if (danmoInformationCopy11.getDanmoInformationBar() == null) {
            danmoInformationCopy11.setDanmoInformationBar(new DanmoInformationBar());
        }

        if (danmoInformationCopy11.getDanmoInformationPhotosList() == null) {
            danmoInformationCopy11.setDanmoInformationPhotosList(Collections.singletonList(new DanmoInformationPhotos()));
        }

        if (danmoInformationCopy11.getDanmoCollectShellfishList() == null) {
            danmoInformationCopy11.setDanmoCollectShellfishList(Collections.singletonList(new DanmoCollectShellfish()));
        }

        if (danmoInformationCopy11.getDanmoInformationMapTitleList() == null) {
            danmoInformationCopy11.setDanmoInformationMapTitleList(Collections.singletonList(new DanmoInformationMapTitle()));
        }

        if (danmoInformationCopy11.getDanmoInformationVideoList() == null) {
            danmoInformationCopy11.setDanmoInformationVideoList(Collections.singletonList(new DanmoInformationVideo()));
        }

        if (danmoInformationCopy11.getDanmoInformationContentList() == null) {
            danmoInformationCopy11.setDanmoInformationContentList(Collections.singletonList(new DanmoInformationContent()));
        }

        if (danmoInformationCopy11.getDanmoInformationVideoList() == null) {
            danmoInformationCopy11.setDanmoInformationVideoList(Collections.singletonList(new DanmoInformationVideo()));
        }

        if (danmoInformationCopy11.getDanmoInformationFlagshipList() == null) {
            danmoInformationCopy11.setDanmoInformationFlagshipList(Collections.singletonList(new DanmoInformationFlagship()));
        }

        return Result.success(danmoInformationCopy11);
    }

    /**
     * 查询个人信息新列表
     *
     * @param danmoInformationCopy1 个人信息新
     * @return 个人信息新
     */
    @Override
    public List<DanmoInformationCopy1> selectDanmoInformationCopy1List(DanmoInformationCopy1 danmoInformationCopy1) {
//        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
//        List<DanmoInformationCopy1> danmoInformationCopy1s = danmoInformationCopy1Mapper.selectDanmoInformationCopy1Lists(danmoInformationCopy1, tableName);
        List<PersonBaseInfoVO> personBaseInfo = danmoPersonInfoService.getPersonBaseInfo(personMapper.to(danmoInformationCopy1));
        return personBaseInfo.stream().filter(a -> StrUtil.isNotEmpty(a.getName())).map(personBaseInfoVO -> {
            DanmoInformationCopy1 danmoInformationCopy2 = new DanmoInformationCopy1();
            BeanUtil.copyProperties(personBaseInfoVO, danmoInformationCopy2);
            return danmoInformationCopy2;
        }).collect(Collectors.toList());
    }

    @Override
    public List<PersonNameVO> getPersonName(DanmoInformationCopy1 danmoInformationCopy1) {
        PersonBaseInfoDTO personBaseInfoDTO = new PersonBaseInfoDTO();
        personBaseInfoDTO.setAssociationId(danmoInformationCopy1.getAssociation());
        personBaseInfoDTO.setAssociationTypeId(danmoInformationCopy1.getAssociationType());
        personBaseInfoDTO.setName(danmoInformationCopy1.getName());
        List<PersonBaseInfoVO> personBaseInfo = danmoPersonInfoService.getPersonBaseInfo(personBaseInfoDTO);
        return personBaseInfo.stream().collect(Collectors.toMap(
                PersonBaseInfoVO::getId,
                a -> {
                    PersonNameVO personNameVO = new PersonNameVO();
                    personNameVO.setId(a.getId());
                    personNameVO.setName(a.getName());
                    PersonAddressVO personAddressVO = new PersonAddressVO();
                    personAddressVO.setAddressCity(a.getAddressCity());
                    personAddressVO.setAddressCounty(a.getAddressCounty());
                    personAddressVO.setAddressEntry(a.getAddressEntry());
                    List<PersonAddressVO> objects = new ArrayList<>();
                    objects.add(personAddressVO);
                    personNameVO.setAddressList(objects);
                    return personNameVO;
                },
                (vo1, vo2) -> {
                    vo1.getAddressList().addAll(vo2.getAddressList());
                    return vo1;
                }
        )).values().stream().toList();
    }

    private String determineTable(Long associationType) {
        if (associationType == null) {
            return "danmo_information";
        }
        if (associationType == 1 || associationType == 7) {
            return "danmo_information_guo";
        }
        if (associationType == 2 || associationType == 8) {
            return "danmo_information_sheng";
        }
        if (associationType == 3 || associationType == 9) {
            return "danmo_information_shi";
        }
        if (associationType == 4 || associationType == 10) {
            return "danmo_information_gu";
        }
        if (associationType == 5 || associationType == 11) {
            return "danmo_information_she";
        }
        if (associationType == 6 || associationType == 12) {
            return "danmo_information_xing";
        } else {
            return "danmo_information_copy1";
        }
    }


    @Autowired
    private DanmoInformationBarMapper danmoInformationBarMapper;
    @Autowired
    private DanmoInformationContentMapper danmoInformationContentMapper;

    @Autowired
    private DanmoInformationCalligrapherPositionMapper danmoInformationCalligrapherPositionMapper;
    @Autowired
    private DanmoPersonalPicturesMapper danmoPersonalPicturesMapper;

    @Autowired
    private DanmoInformationMapMapper danmoInformationMapMapper;

    @Autowired
    private DanmoInformationMapper danmoInformationMapper;

    @Autowired
    private DanmoInformationMapTitleMapper danmoInformationMapTitleMapper;

    @Autowired
    private DanmoAssociationTypeMapper danmoAssociationTypeMapper;

    @Autowired
    private DanmoInformationMassServiceImpl danmoInformationMassService;

    @Autowired
    private DanmoInformationServiceImpl danmoInformationService;


    private final IDanmoInformationMapTitleService iDanmoInformationMapTitleService;

    private final IDanmoInformationMapService iDanmoInformationMapService;

    private final IDanmoInformationBarService iDanmoInformationBarService;

    /**
     * 新增个人信息新
     *
     * @param danmoInformationCopy1 个人信息新
     * @return 结果
     */
    @Override
    public Result insertDanmoInformationCopy1(DanmoInformationCopy1 danmoInformationCopy1) throws UnsupportedEncodingException {
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());

        if (danmoInformationCopy1.getAssociationType() == 5 || danmoInformationCopy1.getAssociationType() == 11 ){
            DanmoInformationMass danmoInformationMass = new DanmoInformationMass();
            danmoInformationMass.setAssociation(danmoInformationCopy1.getAssociation());
            danmoInformationMass.setMassId(danmoInformationCopy1.getMassId());
            for (DanmoInformationMass informationMass : danmoInformationMassService.selectDanmoInformationMassList(danmoInformationMass)) {
                 informationMass.setNumber(informationMass.getNumber()+1);
                danmoInformationMassService.updateDanmoInformationMass(informationMass);
            }
        }

        if (null != danmoInformationCopy1.getCondition() && danmoInformationCopy1.getCondition()!=0) {
            Result result = DanmoCheck(danmoInformationCopy1);
            return result;
        }

        addDanmoInformationCopy1(danmoInformationCopy1, tableName);

        Long id = danmoInformationCopy1.getId();

        if (!danmoInformationCopy1.getRemark().equals("存草稿")){
            DanmoAssociationType danmoAssociationType = danmoAssociationTypeMapper.selectDanmoAssociationTypeById(danmoInformationCopy1.getAssociationType());
            danmoAssociationType.setNumber(danmoAssociationType.getNumber() + 1L);
            danmoAssociationTypeMapper.updateDanmoAssociationType(danmoAssociationType);
        }


        addDanmoPersonalPictures(danmoInformationCopy1, id);

        addDanmoInformationMapTitle(danmoInformationCopy1, id);

        addDanmoInformationBar(danmoInformationCopy1, id);

        addDanmoInformationContent(danmoInformationCopy1, id);

        addDanmoInformationCalligrapherPosition(danmoInformationCopy1, id);

        DanmoInformation danmoInformation = new DanmoInformation();
        danmoInformation.setId(id);
        danmoInformation.setName(danmoInformationCopy1.getDanmoInformationBar().getChineseName());
        danmoInformation.setCreateTime(DateUtils.getNowDate());
        danmoInformation.setAddressEntry(danmoInformationCopy1.getAddressEntry());
        danmoInformation.setAddressCity(danmoInformationCopy1.getAddressCity());
        danmoInformation.setAddressCounty(danmoInformationCopy1.getAddressCounty());
        danmoInformation.setUserId(danmoInformationCopy1.getUserId());
        danmoInformation.setRemark(danmoInformationCopy1.getRemark());
        danmoInformation.setAssociation(danmoInformationCopy1.getAssociation());
        danmoInformation.setAssociationType(danmoInformationCopy1.getAssociationType());
        danmoInformation.setCertificate(danmoInformationCopy1.getCertificate());
        danmoInformation.setCertificateNumber(danmoInformationCopy1.getCertificateNumber());
        danmoInformation.setYear(danmoInformationCopy1.getYear());
        danmoInformation.setPositions(danmoInformationCopy1.getPositions());
        danmoInformation.setDynastiesId(danmoInformationCopy1.getDynastiesId());
        danmoInformation.setMassId(danmoInformationCopy1.getMassId());
        danmoInformation.setIdReverse(danmoInformationCopy1.getIdReverse());
        danmoInformation.setIdFront(danmoInformationCopy1.getIdFront());
        danmoInformationService.insertDanmoInformation(danmoInformation);
        return Result.success(danmoInformationCopy1, "添加成功");
    }

    /**
     * 添加个人信息职位
     * @param danmoInformationCopy1
     * @param id
     */
    private void addDanmoInformationCalligrapherPosition(DanmoInformationCopy1 danmoInformationCopy1, Long id) {
        DanmoInformationCalligrapherPosition danmoInformationCalligrapherPosition = new DanmoInformationCalligrapherPosition();
        danmoInformationCalligrapherPosition.setInformationId(id);
        if (danmoInformationCopy1.getPositionId() != null) {
            danmoInformationCalligrapherPosition.setPositionId(danmoInformationCopy1.getPositionId());
            danmoInformationCalligrapherPositionMapper.insertDanmoInformationCalligrapherPosition(danmoInformationCalligrapherPosition);

        }
    }

    /**
     * 添加个人信息内容
     * @param danmoInformationCopy1
     * @param id
     * @throws UnsupportedEncodingException
     */

    private void addDanmoInformationContent(DanmoInformationCopy1 danmoInformationCopy1, Long id) throws UnsupportedEncodingException {
        if (danmoInformationCopy1.getDanmoInformationPhotosList() != null && danmoInformationCopy1.getDanmoInformationPhotosList().size() > 0) {
            for (DanmoInformationContent danmoInformationContent : danmoInformationCopy1.getDanmoInformationContentList()) {
                danmoInformationContent.setInformationId(id);
                String jsonObject = URLDecoder.decode(danmoInformationContent.getRichText(), "utf-8");
                danmoInformationContent.setRichText(jsonObject);
                danmoInformationContentMapper.insertDanmoInformationContent(danmoInformationContent);
            }
        }
    }


    /**
     * 新增协会信息
     * @param personPositionList
     * @param id
     */
    public void addDanmoPersonPosition(List<PersonPositionDTO> personPositionList, Long id){
        if(CollUtil.isEmpty(personPositionList)){
            return;
        }
        List<DanmoPersonPosition> list = danmoPersonPositionService.lambdaQuery().eq(DanmoPersonPosition::getPersonId, id).list();
        personPositionList.forEach(a ->{
            long count = list.stream().filter(b -> {
                return ObjectUtil.equal(a.getAssociationId(),b.getAssociationId()) && ObjectUtil.equal(a.getAssociationTypeId(),b.getAssociationTypeId())
                        && ObjectUtil.equal(a.getPositionId(),b.getPositionId()) && ObjectUtil.equal(a.getMassId(),b.getMassId()) && ObjectUtil.equal(a.getAddressCity(),b.getAddressCity())
                        && ObjectUtil.equal(a.getAddressCounty(),b.getAddressCounty()) && ObjectUtil.equal(a.getAddressEntry(),b.getAddressEntry()) && ObjectUtil.equal(a.getSeveral(),b.getSeveral());
            }).count();
            if(count == 0){
                a.setPersonId(id);
                danmoPersonPositionService.save(personMapper.to(a));
            }
        });
    }

    /**
     * 添加个人信息内容
     * @param list
     * @param id
     * @throws UnsupportedEncodingException
     */

    public void addDanmoInformationContent(List<DanmoInformationContent> list, Long id){
        if(CollUtil.isEmpty(list)){
            return;
        }
        list.forEach(a ->{
            DanmoInformationContent danmoInformationContent = iDanmoInformationContentService.lambdaQuery().eq(DanmoInformationContent::getInformationId, id)
                    .eq(DanmoInformationContent::getParentHeading, a.getParentHeading())
                    .one();
            if(null != danmoInformationContent){
                a.setContentId(danmoInformationContent.getContentId());
            }
            a.setInformationId(id);
            if(StrUtil.isNotEmpty(a.getRichText())){
                String jsonObject = null;
                try {
                    jsonObject = URLDecoder.decode(a.getRichText(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                a.setRichText(jsonObject);
            }
            iDanmoInformationContentService.saveOrUpdate(a);
        });
    }

    /**
     * 添加个人简介
     * @param danmoInformationCopy1
     * @param id
     */
    private void addDanmoInformationBar(DanmoInformationCopy1 danmoInformationCopy1, Long id) {
        DanmoInformationBar danmoInformationBar = danmoInformationCopy1.getDanmoInformationBar();
        if (danmoInformationBar != null && danmoInformationBar.getChineseName() != null) {
            danmoInformationBar.setInformationId(id);
            danmoInformationBarMapper.insertDanmoInformationBar(danmoInformationBar);
            if (danmoInformationCopy1.getDanmoInformationPhotosList()!=null){
                for (DanmoInformationPhotos danmoInformationPhotos : danmoInformationCopy1.getDanmoInformationPhotosList()) {
                    danmoInformationPhotos.setInformationId(id);
                    danmoInformationMapper.insertDanmoInformationPhotos(danmoInformationPhotos);
                }
            }

        }
    }


    /**
     * 添加个人简介
     * @param danmoInformationBar
     * @param id
     */
    public void addDanmoInformationBar(DanmoInformationBar danmoInformationBar, Long id,List<DanmoInformationPhotos> danmoInformationPhotosList,Long userId) {
        if(null == danmoInformationBar && StrUtil.isNotEmpty(danmoInformationBar.getChineseName())){
            return;
        }
        DanmoInformationBar informationBar = iDanmoInformationBarService.lambdaQuery().eq(DanmoInformationBar::getInformationId, id)
                .one();
        if (informationBar != null) {
            danmoInformationBar.setId(informationBar.getId());
        }
        danmoInformationBar.setInformationId(id);
        danmoInformationBar.setUserId(userId);
        iDanmoInformationBarService.saveOrUpdate(danmoInformationBar);
        if(CollUtil.isNotEmpty(danmoInformationPhotosList)){
            // 删除原有的图片重新新增
            List<DanmoInformationPhotos> list = iDanmoInformationPhotosService.lambdaQuery().eq(DanmoInformationPhotos::getInformationId, id).list();
            iDanmoInformationPhotosService.removeBatchByIds(list.stream().map(DanmoInformationPhotos::getId).collect(Collectors.toList()));
            danmoInformationPhotosList.forEach(a ->{
                a.setInformationId(id);
                danmoInformationMapper.insertDanmoInformationPhotos(a);
            });
        }
    }

    /**
     * 添加个人图片
     * @param danmoInformationCopy1
     * @param id
     */
    private void addDanmoPersonalPictures(DanmoInformationCopy1 danmoInformationCopy1, Long id) {
        List<DanmoPersonalPictures> danmoPersonalPicturesList = danmoInformationCopy1.getDanmoPersonalPicturesList();
        if (danmoPersonalPicturesList != null && danmoPersonalPicturesList.size() > 0) {
            for (DanmoPersonalPictures danmoPersonalPictures : danmoPersonalPicturesList) {
                danmoPersonalPictures.setInformationId(id);
                danmoPersonalPicturesMapper.insertDanmoPersonalPictures(danmoPersonalPictures);
            }
        }
    }

    /**
     * 保存个人图片
     * @param danmoPersonalPicturesList
     * @param id
     */
    public void addDanmoPersonalPictures(List<DanmoPersonalPictures> danmoPersonalPicturesList, Long id){
        if(CollUtil.isEmpty(danmoPersonalPicturesList)){
            return;
        }
        List<DanmoPersonalPictures> list = iDanmoPersonalPicturesService.lambdaQuery().eq(DanmoPersonalPictures::getInformationId, id).list();
        if(CollUtil.isNotEmpty(list)){
            iDanmoPersonalPicturesService.removeBatchByIds(list.stream().map(DanmoPersonalPictures::getId).collect(Collectors.toList()));
        }
        danmoPersonalPicturesList.forEach(a ->{
            a.setInformationId(id);
            iDanmoPersonalPicturesService.saveOrUpdate(a);
        });

    }

    /**
     * 添加星图
     * @param danmoInformationCopy1
     * @param id
     */
    private void addDanmoInformationMapTitle(DanmoInformationCopy1 danmoInformationCopy1, Long id) {
        List<DanmoInformationMapTitle> danmoInformationMapTitleList = danmoInformationCopy1.getDanmoInformationMapTitleList();
        if (danmoInformationMapTitleList != null && danmoInformationMapTitleList.size() > 0) {
            for (DanmoInformationMapTitle danmoInformationMapTitle : danmoInformationMapTitleList) {
                danmoInformationMapTitle.setInformationId(id);
                danmoInformationMapTitle.setViews(0L);
                danmoInformationMapTitleMapper.insertDanmoInformationMapTitle(danmoInformationMapTitle);
                List<DanmoInformationMap> danmoInformationMapList = danmoInformationMapTitle.getDanmoInformationMapList();
                if (danmoInformationMapList != null || !danmoInformationMapList.get(0).getName().equals("")) {
                    for (DanmoInformationMap danmoInformationMap : danmoInformationMapList) {
                        danmoInformationMap.setInformationId(id);
                        danmoInformationMap.setMapTitleId(danmoInformationMapTitle.getId());
                        danmoInformationMapMapper.insertDanmoInformationMap(danmoInformationMap);
                    }
                }
            }
        }
    }

    /**
     * 保存星图
     * @param danmoInformationMapTitleList
     * @param id
     */
    public void addDanmoInformationMapTitle(List<DanmoInformationMapTitle> danmoInformationMapTitleList, Long id) {
        if(CollUtil.isNotEmpty(danmoInformationMapTitleList)){
            danmoInformationMapTitleList.forEach(a ->{
                DanmoInformationMapTitle danmoInformationMapTitle = iDanmoInformationMapTitleService.lambdaQuery().eq(DanmoInformationMapTitle::getInformationId, id)
                        .eq(DanmoInformationMapTitle::getTitle, a.getTitle()).one();
                if(null != danmoInformationMapTitle){
                    a.setId(danmoInformationMapTitle.getId());
                }else {
                    a.setViews(0L);
                }
                a.setInformationId(id);
                iDanmoInformationMapTitleService.saveOrUpdate(a);
                a.getDanmoInformationMapList().forEach(b ->{
                    if(StrUtil.isNotEmpty(b.getName())){
                        DanmoInformationMap danmoInformationMap = iDanmoInformationMapService.lambdaQuery()
                                .eq(DanmoInformationMap::getInformationId, id)
                                .eq(DanmoInformationMap::getMapTitleId, a.getId())
                                .eq(DanmoInformationMap::getName, b.getName()).one();
                        if(null != danmoInformationMap){
                            b.setId(danmoInformationMap.getId());
                        }
                        b.setInformationId(id);
                        b.setMapTitleId(a.getId());
                        iDanmoInformationMapService.saveOrUpdate(b);
                    }
                });
            });
        }

    }

    /**
     *  添加个人信息
     * @param danmoInformationCopy1
     * @param tableName
     */
    private void addDanmoInformationCopy1(DanmoInformationCopy1 danmoInformationCopy1, String tableName) {
        if (danmoInformationCopy1.getDanmoInformationBar() != null){
            danmoInformationCopy1.setName(danmoInformationCopy1.getDanmoInformationBar().getChineseName());
            danmoInformationCopy1.setCreateTime(DateUtils.getNowDate());
            danmoInformationCopy1Mapper.insertDanmoInformationCopy1(danmoInformationCopy1, tableName);
        }
    }

    // 辅助方法：检查字符串是否为空或 null
    private boolean isNullOrEmpty(String str) {
        return str == null || str.isEmpty();
    }

    private Result DanmoCheck(DanmoInformationCopy1 danmoInformationCopy1) {



       // 检查协会
        if (danmoInformationCopy1.getAssociation() == null) {
            return Result.error("协会不能为空");
        }

     // 检查协会类型
        if (danmoInformationCopy1.getAssociationType() == null) {
            return Result.error("协会类型不能为空");
        }

// 检查入会省
        if (danmoInformationCopy1.getAddressEntry() == null) {
            return Result.error("入会省不能为空");
        }

// 检查入会市
        if (danmoInformationCopy1.getAddressCity() == null) {
            return Result.error("入会市不能为空");
        }

// 检查入会县
        if (danmoInformationCopy1.getAddressCounty() == null) {
            return Result.error("入会县不能为空");
        }

        if (danmoInformationCopy1.getAssociationType() != 6){
            // 检查证书编号
            if (danmoInformationCopy1.getCertificateNumber() == null) {
                return Result.error("证书编号不能为空");
            }

// 检查职位ID和第几届
            if (danmoInformationCopy1.getPositionId() != null && danmoInformationCopy1.getPositionId() == 2) {
                if (danmoInformationCopy1.getSeveral() == null) {
                    return Result.error("第几届不能为空");
                }
            }
//            // 检查身份证反面
//            if (isNullOrEmpty(danmoInformationCopy1.getIdReverse())) {
//                return Result.error("身份证反面不能为空");
//            }
//
//            // 检查身份证正面
//            if (isNullOrEmpty(danmoInformationCopy1.getIdFront())) {
//                return Result.error("身份证正面不能为空");
//            }

// 检查职业
            if (isNullOrEmpty(danmoInformationCopy1.getDanmoInformationBar().getVocational())) {
                return Result.error("职业不能为空");
            }

// 检查照片
            if (danmoInformationCopy1.getDanmoInformationPhotosList() == null || danmoInformationCopy1.getDanmoInformationPhotosList().size() == 0) {
                return Result.error("请上传照片");
            }

// 检查个人简介
            if (isNullOrEmpty(danmoInformationCopy1.getDanmoInformationBar().getProfile())) {
                return Result.error("个人简介不能为空");
            }

            // 检查姓名
            if (isNullOrEmpty(danmoInformationCopy1.getDanmoInformationBar().getChineseName())) {
                return Result.error("姓名不能为空");
            }
        }




        return null;
    }

    /**
     * 修改个人信息新
     *
     * @param danmoInformationCopy1 个人信息新
     * @return 结果
     */
    @Override
    public Result updateDanmoInformationCopy1(DanmoInformationCopy1 danmoInformationCopy1) throws UnsupportedEncodingException {
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
        Long id = danmoInformationCopy1.getId();
        danmoInformationCopy1.setName(danmoInformationCopy1.getDanmoInformationBar().getChineseName());
        danmoInformationCopy1.setUpdateTime(DateUtils.getNowDate());
        danmoInformationCopy1Mapper.updateDanmoInformationCopy1(danmoInformationCopy1, tableName);


//            先将所有旧数据全部删掉
        danmoPersonalPicturesMapper.deleteDanmoPersonalPicturesByInformationId(danmoInformationCopy1.getId());
        danmoInformationMapTitleMapper.deleteDanmoInformationMapTitleByInformationId(id);
        List<DanmoInformationMapTitle> danmoInformationMapTitleList1 = danmoInformationCopy1.getDanmoInformationMapTitleList();
        if (danmoInformationMapTitleList1 != null) {
            for (DanmoInformationMapTitle danmoInformationMapTitle : danmoInformationMapTitleList1) {
                Long mapTitleId = danmoInformationMapTitle.getId();
                danmoInformationMapMapper.deleteDanmoInformationMapByMapTitleId(mapTitleId);
            }
        }
        danmoInformationBarMapper.deleteDanmoInformationBarByInformationId(id);
        danmoInformationMapper.deleteDanmoInformationPhotosByInformationId(id);
        danmoInformationCalligrapherPositionMapper.deleteDanmoInformationCalligrapherPositionByInformationId(id);
        danmoInformationContentMapper.deleteDanmoInformationContentByContentInformationId(id);

        List<DanmoPersonalPictures> danmoPersonalPicturesList = danmoInformationCopy1.getDanmoPersonalPicturesList();
        if (danmoPersonalPicturesList != null) {
            for (DanmoPersonalPictures danmoPersonalPictures : danmoPersonalPicturesList) {
                danmoPersonalPictures.setInformationId(id);
                danmoPersonalPicturesMapper.insertDanmoPersonalPictures(danmoPersonalPictures);
            }
        }


        List<DanmoInformationMapTitle> danmoInformationMapTitleList = danmoInformationCopy1.getDanmoInformationMapTitleList();
        if (danmoInformationMapTitleList != null || !danmoInformationMapTitleList.get(0).getTitle().equals("")) {
            for (DanmoInformationMapTitle danmoInformationMapTitle : danmoInformationMapTitleList) {
                danmoInformationMapTitle.setInformationId(id);
                danmoInformationMapTitle.setViews(0L);
                danmoInformationMapTitleMapper.insertDanmoInformationMapTitle(danmoInformationMapTitle);
                List<DanmoInformationMap> danmoInformationMapList = danmoInformationMapTitle.getDanmoInformationMapList();
                if (danmoInformationMapList != null || !danmoInformationMapList.get(0).getName().equals("")) {
                    for (DanmoInformationMap danmoInformationMap : danmoInformationMapList) {
                        danmoInformationMap.setInformationId(id);
                        danmoInformationMap.setMapTitleId(danmoInformationMapTitle.getId());
                        danmoInformationMapMapper.insertDanmoInformationMap(danmoInformationMap);
                    }
                }
            }
        }

        DanmoInformationBar danmoInformationBar = danmoInformationCopy1.getDanmoInformationBar();
        if (danmoInformationBar != null) {
            danmoInformationBar.setInformationId(id);
            danmoInformationBarMapper.insertDanmoInformationBar(danmoInformationBar);
            for (DanmoInformationPhotos danmoInformationPhotos : danmoInformationCopy1.getDanmoInformationPhotosList()) {
                danmoInformationPhotos.setInformationId(id);
                danmoInformationMapper.insertDanmoInformationPhotos(danmoInformationPhotos);
            }
        }

        for (DanmoInformationContent danmoInformationContent : danmoInformationCopy1.getDanmoInformationContentList()) {
            danmoInformationContent.setInformationId(id);
            String jsonObject = URLDecoder.decode(danmoInformationContent.getRichText(), "utf-8");
            danmoInformationContent.setRichText(jsonObject);
            danmoInformationContentMapper.insertDanmoInformationContent(danmoInformationContent);
        }
        DanmoInformationCalligrapherPosition danmoInformationCalligrapherPosition = new DanmoInformationCalligrapherPosition();
        danmoInformationCalligrapherPosition.setInformationId(id);
        danmoInformationCalligrapherPosition.setPositionId(danmoInformationCopy1.getPositionId());
        danmoInformationCalligrapherPositionMapper.insertDanmoInformationCalligrapherPosition(danmoInformationCalligrapherPosition);

        return Result.success(danmoInformationCopy1, "修改成功");

    }

    /**
     * 批量删除个人信息新
     *
     * @param ids 需要删除的个人信息新主键
     * @return 结果
     */
    @Override
    public Result deleteDanmoInformationCopy1ByIds(Long[] ids) {
        danmoInformationCopy1Mapper.deleteDanmoInformationCopy1ByIds(ids);
        return Result.success(ids, "删除成功");
    }

    /**
     * 删除个人信息新信息
     *
     * @param id 个人信息新主键
     * @return 结果
     */
    @Override
    public Result deleteDanmoInformationCopy1ById(Long id) {
        danmoInformationCopy1Mapper.deleteDanmoInformationCopy1ById(id);
        return Result.success(id, "删除成功");
    }

    @Override
    public List<String> selectListyears(DanmoInformationCopy1 danmoInformationCopy1) {
//        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
//        // 使用 Set 来去重年份
//        Set<String> yearSet = new HashSet<>();
//
//        // 遍历查询结果，将年份添加到 Set 中，Set 会自动去重
//        for (DanmoInformationCopy1 danmoInformationCopy1s : danmoInformationCopy1Mapper.selectAncient(danmoInformationCopy1, tableName)) {
//            String year = danmoInformationCopy1s.getYear();
//            if (year != null) {
//                yearSet.add(year);
//            }
//        }
//        // 排序 List（升序）
//        List<String> sortedYears = new ArrayList<>(yearSet);
//        Collections.sort(sortedYears);


        List<DanmoPersonPosition> list = danmoPersonPositionService.lambdaQuery()
                .eq(null != danmoInformationCopy1.getPositions(),DanmoPersonPosition::getPositions,
                        danmoInformationCopy1.getPositions() != null ? danmoInformationCopy1.getPositions().intValue() : 0)
                .eq(null != danmoInformationCopy1.getAssociationType(),DanmoPersonPosition::getAssociationTypeId, danmoInformationCopy1.getAssociationType())
                .eq(null != danmoInformationCopy1.getAssociation(),DanmoPersonPosition::getAssociationId, danmoInformationCopy1.getAssociation())
                .eq(StrUtil.isNotEmpty(danmoInformationCopy1.getAddressEntry()),DanmoPersonPosition::getAddressEntry, danmoInformationCopy1.getAddressEntry())
                .isNotNull(DanmoPersonPosition::getYear)
                .groupBy(DanmoPersonPosition::getYear).select(DanmoPersonPosition::getYear)
                .orderByAsc(DanmoPersonPosition::getYear).list();
        return list.stream().map(DanmoPersonPosition::getYear).collect(Collectors.toList());
    }

    @Override
    public List<Long> selectSuccessive(DanmoInformationCopy1 danmoInformationCopy1) {
//        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
//
//        // 使用 Set 来去重年份
//        Set<Long> severals = new HashSet<>();
//
//        // 遍历查询结果，将年份添加到 Set 中，Set 会自动去重
//        for (DanmoInformationCopy1 danmoInformationCopy1s : danmoInformationCopy1Mapper.selectAncient(danmoInformationCopy1, tableName)) {
//            Long several = danmoInformationCopy1s.getSeveral();
//            if (several != null) {
//                severals.add(several);
//            }
//        }
//        // 排序 List（升序）
//        List<Long> sortedSeveral = new ArrayList<>(severals);
//        Collections.sort(sortedSeveral);
//        return sortedSeveral;

        List<DanmoPersonPosition> list = danmoPersonPositionService.lambdaQuery()
                .eq(null != danmoInformationCopy1.getAssociationType(),DanmoPersonPosition::getAssociationTypeId, danmoInformationCopy1.getAssociationType())
                .eq(null != danmoInformationCopy1.getAssociation(),DanmoPersonPosition::getAssociationId, danmoInformationCopy1.getAssociation())
                .eq(StrUtil.isNotEmpty(danmoInformationCopy1.getAddressEntry()),DanmoPersonPosition::getAddressEntry, danmoInformationCopy1.getAddressEntry())
                .isNotNull(DanmoPersonPosition::getSeveral)
                .groupBy(DanmoPersonPosition::getSeveral).select(DanmoPersonPosition::getSeveral)
                .orderByAsc(DanmoPersonPosition::getSeveral).list();
        return list.stream().map(DanmoPersonPosition::getSeveral).collect(Collectors.toList());

    }

    @Override
    public List<Map<String, List<DanmoInformationCopy1>>> selectList(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

        // 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<DanmoInformationCopy1>> groupedData = new TreeMap<>();

        // 首先初始化所有字母（A-Z）和 "others" 的空列表
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }

        // 按照拼音首字母分组
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取拼音首字母（不会修改原来的 name 字段）
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());


            // 将数据根据拼音首字母分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())
                    .add(information);
        }

        // 将分组结果转换为List形式，方便返回
        List<Map<String, List<DanmoInformationCopy1>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformationCopy1>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformationCopy1>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

        // 返回结果
        return result;

    }

    @Override
    public List<Map<String, Object>> select(DanmoInformationCopy1 danmoInformationCopy1) {
        PersonBaseInfoDTO personBaseInfoDTO = new PersonBaseInfoDTO();
        personBaseInfoDTO.setPositions(danmoInformationCopy1.getPositions());
        personBaseInfoDTO.setAssociationId(danmoInformationCopy1.getAssociation());
        personBaseInfoDTO.setAssociationTypeId(danmoInformationCopy1.getAssociationType());
        personBaseInfoDTO.setYear(danmoInformationCopy1.getYear());
        List<PersonBaseInfoVO> danmoInformations = danmoPersonInfoService.getPersonBaseInfo(personBaseInfoDTO);

        // 获取所有数据
//        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 用于存储每个省份的人数
        Map<String, Integer> provinceCountMap = new HashMap<>();

// 首先，统计每个省份的总人数
        for (PersonBaseInfoVO info : danmoInformations) {
            String province = info.getAddressEntry(); // 获取省份
            provinceCountMap.put(province, provinceCountMap.getOrDefault(province, 0) + 1);
        }

// 按照省份拼音首字母分组
        Map<String, List<Map<String, Object>>> groupedData = new LinkedHashMap<>();

// 初始化所有字母分组（A-Z）以及一个 "others" 分组
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }
        groupedData.put("others", new ArrayList<>()); // 用于处理非A-Z字母的情况

// 按照每个省份处理
        for (PersonBaseInfoVO info : danmoInformations) {
            String province = info.getAddressEntry(); // 获取省份

            // 获取拼音首字母
            String firstLetter = GetPinyinInitial.getPinyinInitial(province);

            // 如果拼音首字母是"Z"且省份是"重庆"，强制改为"C"
            if ("重庆市".equals(province) && "Z".equals(firstLetter)) {
                firstLetter = "C";
            }

            // 如果拼音首字母不是A-Z，归类到"others"
            if (!firstLetter.matches("[A-Z]")) {
                firstLetter = "others";
            }

            // 获取拼音首字母对应的分组
            List<Map<String, Object>> letterGroup = groupedData.computeIfAbsent(firstLetter, k -> new ArrayList<>());

            // 检查该省份是否已存在
            Optional<Map<String, Object>> existingGroup = letterGroup.stream()
                    .filter(group -> group.containsKey("province") && group.get("province").equals(province))
                    .findFirst();

            if (!existingGroup.isPresent()) {
                // 如果该省份不存在，创建新组并加入
                Map<String, Object> provinceGroup = new LinkedHashMap<>();
                provinceGroup.put("province", province);
                provinceGroup.put("people", provinceCountMap.get(province)); // 使用已经统计好的省份人数

                // 为该省份设置一个包含相关数据的列表
                List<PersonBaseInfoVO> provinceList = danmoInformations.stream()
                        .filter(item -> item.getAddressEntry().equals(province))
                        .collect(Collectors.toList());
                provinceGroup.put("list", provinceList);

                // 将该省份的分组加入到字母分组中
                letterGroup.add(provinceGroup);
            }
        }

// 将按拼音首字母分组后的数据转化为目标格式
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, List<Map<String, Object>>> entry : groupedData.entrySet()) {
            Map<String, Object> group = new LinkedHashMap<>();
            group.put("initials", entry.getKey());
            group.put("initialsList", entry.getValue());
            result.add(group);
        }
        return result;
    }








    @Override
    public List<Map<String, Object>> selectCouncil(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取所有数据
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);


// 存放数据的 List
        List<Map<String, Object>> dataList = new ArrayList<>();

// 存储所有大类和子类数据
        Map<String, Map<String, List<DanmoInformationCopy1>>> allDataMap = new HashMap<>();

// 遍历所有 DanmoInformation 对象，将数据根据大类（如"理事"）和子类（如"常务理事"、"普通理事"）进行分类
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取大类（例如"理事"）和子类（例如"常务理事"或"普通理事"）
            String category = information.getGrade();  // 假设可以通过该字段获取大类（如"理事"）
            String subCategory = information.getPositionName();  // 假设通过positionName获取子类（如"常务理事"、"普通理事"）

            // 初始化大类映射
            allDataMap.putIfAbsent(category, new HashMap<>());
            Map<String, List<DanmoInformationCopy1>> subCategoryMap = allDataMap.get(category);

            // 初始化子类映射
            subCategoryMap.putIfAbsent(subCategory, new ArrayList<>());

            // 将该人员信息加入到对应的子类列表中
            subCategoryMap.get(subCategory).add(information);
        }

// 生成最终数据列表
        for (Map.Entry<String, Map<String, List<DanmoInformationCopy1>>> entry : allDataMap.entrySet()) {
            String category = entry.getKey();  // 如"理事"
            Map<String, List<DanmoInformationCopy1>> subCategories = entry.getValue();

            // 创建一个新的 Map 用于存储最终的数据
            Map<String, Object> categoryMapResult = new HashMap<>();
            categoryMapResult.put("Position", category);  // 大类名称

            // 计算总人数（所有子类的总人数）
            int totalPeople = subCategories.values().stream().mapToInt(List::size).sum();
            categoryMapResult.put("people", totalPeople);

            // 创建 positionObject 内容，存储子类及其人员信息
            Map<String, Object> positionObject = new HashMap<>();
            positionObject.put("occupation", category);  // 大类名称
            positionObject.put("occupationList", new ArrayList<Map<String, Object>>());

            // 将各个子类的信息加入到 occupationList 中
            for (Map.Entry<String, List<DanmoInformationCopy1>> subCategoryEntry : subCategories.entrySet()) {
                String subCategoryName = subCategoryEntry.getKey();  // 子类名称，如"常务理事"、"普通理事"
                List<DanmoInformationCopy1> subCategoryList = subCategoryEntry.getValue();

                // 创建子类信息 Map
                Map<String, Object> subCategoryMap = new HashMap<>();
                subCategoryMap.put("subCategory", subCategoryName);
                subCategoryMap.put("subCategoryPeople", subCategoryList.size());

                // 将该子类人员详细信息添加到子类列表
                List<Map<String, Object>> subCategoryDetails = new ArrayList<>();
                for (DanmoInformationCopy1 personalInfo : subCategoryList) {
                    Map<String, Object> personalInfoMap = new HashMap<>();
                    personalInfoMap.put("personalInfo", personalInfo);  // 将个人信息放入 Map 中
                    subCategoryDetails.add(personalInfoMap);
                }

                subCategoryMap.put("personalDetails", subCategoryDetails);

                // 将子类信息添加到 positionObject 的 occupationList 中
                ((List<Map<String, Object>>) positionObject.get("occupationList")).add(subCategoryMap);
            }

            // 将 positionObject 放入最终的 categoryMapResult 中
            categoryMapResult.put("positionObject", positionObject);

            // 将构造好的 categoryMapResult 加入最终数据列表
            dataList.add(categoryMapResult);
        }

        return dataList;

    }

    @Override
    public DanmoProvincesCities<List<Map<String, List<PersonBaseInfoVO>>>> selectCounty(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取 DanmoInformation 列表
//        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

        List<PersonBaseInfoVO> danmoInformations = danmoPersonInfoService.getPersonBaseInfo(personMapper.to(danmoInformationCopy1));


        DanmoProvincesCities<List<Map<String, List<PersonBaseInfoVO>>>> danmoProvincesCities = new DanmoProvincesCities<>();

        // 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<PersonBaseInfoVO>> groupedData = new TreeMap<>();

        // 首先初始化所有字母（A-Z）和 "others" 的空列表
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }

        // 按照拼音首字母分组
        for (PersonBaseInfoVO information : danmoInformations) {
            // 获取拼音首字母（不会修改原来的 name 字段）
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());
            danmoProvincesCities.setProvince(information.getAddressCounty());

            // 将数据根据拼音首字母分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())
                    .add(information);
        }

        // 将分组结果转换为List形式，方便返回
        List<Map<String, List<PersonBaseInfoVO>>> result = new ArrayList<>();
        for (Map.Entry<String, List<PersonBaseInfoVO>> entry : groupedData.entrySet()) {
            Map<String, List<PersonBaseInfoVO>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());

//        int count = danmoInformationCopy1Mapper.statistics(tableName, danmoInformationCopy1);
        Long count = danmoPersonInfoService.statistics(danmoInformationCopy1);

        danmoProvincesCities.setPeople(count.intValue());

        danmoProvincesCities.setList(result);
        // 返回结果
        return danmoProvincesCities;
    }

    @Override
    public List<Map<String, Object>> queryProvincesCities(DanmoInformationCopy1 danmoInformationCopy1) {
        // 假设 selectDanmoInformationCopy1List 是一个方法，用于获取所有数据
//        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);  // 假设此方法返回数据

        List<PersonBaseInfoVO> danmoInformations = danmoPersonInfoService.getPersonBaseInfo(personMapper.to(danmoInformationCopy1));





// 按省份和城市分组
        Map<String, Map<String, List<PersonBaseInfoVO>>> provinceMap = danmoInformations.stream()
                .collect(Collectors.groupingBy(PersonBaseInfoVO::getAddressEntry,
                        Collectors.groupingBy(PersonBaseInfoVO::getAddressCity)));

// 创建一个包含所有字母的基础结构
        List<Map<String, Object>> resultList = new ArrayList<>();

// 添加所有字母（A 到 Z）的条目
        for (char letter = 'A'; letter <= 'Z'; letter++) {
            Map<String, Object> firstLetterEntry = new LinkedHashMap<>();
            firstLetterEntry.put("firstLetter", String.valueOf(letter));
            firstLetterEntry.put("list", new ArrayList<Map<String, Object>>());
            resultList.add(firstLetterEntry);
        }

// 遍历省份Map，构建最终的列表
        provinceMap.forEach((province, cityMap) -> {
            // 获取省份的首字母并转换为大写
            String firstLetter = GetPinyinInitial.getPinyinInitial(province).toUpperCase();

            // 找到对应字母的条目
            Optional<Map<String, Object>> existingEntry = resultList.stream()
                    .filter(entry -> entry.get("firstLetter").equals(firstLetter))
                    .findFirst();

            // 获取该首字母对应的条目
            if (existingEntry.isPresent()) {
                Map<String, Object> firstLetterEntry = existingEntry.get();
                List<Map<String, Object>> provinceList = (List<Map<String, Object>>) firstLetterEntry.get("list");

                // 创建省份信息
                Map<String, Object> provinceInfo = new LinkedHashMap<>();
                provinceInfo.put("province", province);

                // 计算省份的总人数
                int provincePeople = cityMap.values().stream().mapToInt(List::size).sum();
                provinceInfo.put("people", provincePeople);

                List<Map<String, Object>> cityList = new ArrayList<>();

                // 遍历城市Map，构建城市信息
                cityMap.forEach((city, infoList) -> {
                    Map<String, Object> cityInfo = new LinkedHashMap<>();
                    cityInfo.put("city", city);
                    cityInfo.put("people", infoList.size()); // 每个城市的人数
                    cityInfo.put("list", infoList); // 获取当前城市的人员名单

                    // 将城市信息添加到该省份的城市列表中
                    cityList.add(cityInfo);
                });

                // 添加城市列表到省份信息
                provinceInfo.put("cities", cityList);

                // 将省份信息添加到字母对应的列表中
                provinceList.add(provinceInfo);
            }
        });

// 打印或返回结果
        System.out.println(resultList);
        return resultList;

    }

    @Override
    public DanmoProvincesCities selectCouncilCounty(DanmoInformationCopy1 danmoInformationCopy1) {
// 获取所有 DanmoInformation 数据
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);


// 存放最终结果的 List
        List<Map<String, Object>> dataList = new ArrayList<>();
        DanmoProvincesCities danmoProvincesCities = new DanmoProvincesCities();

// 使用 Map 按职位类别和职位名称分类数据
        Map<String, Map<String, List<DanmoInformationCopy1>>> positionMap = new HashMap<>();

// 遍历所有 DanmoInformation 对象，按类别和职位名称进行分类
        for (DanmoInformationCopy1 information : danmoInformations) {
            String grade = information.getGrade();  // 获取职位类别（如：职位、理事等）
            String positionName = information.getPositionName();  // 获取职位名称（如：常务理事、普通理事等）

            if (grade != null && positionName != null) {
                // 设置省市信息
                danmoProvincesCities.setProvince(information.getAddressCity());

                // 确保职位类别存在
                positionMap.computeIfAbsent(grade, k -> new HashMap<>());

                // 获取该类别下的职位名称 Map
                Map<String, List<DanmoInformationCopy1>> gradeMap = positionMap.get(grade);

                // 确保职位名称存在
                gradeMap.computeIfAbsent(positionName, k -> new ArrayList<>());

                // 添加个人信息到对应职位名称下
                gradeMap.get(positionName).add(information);
            }
        }

// 将 positionMap 转换为最终的 dataList 格式
        for (Map.Entry<String, Map<String, List<DanmoInformationCopy1>>> gradeEntry : positionMap.entrySet()) {
            String positionType = gradeEntry.getKey();  // 职位类别（例如：职位、理事）
            Map<String, List<DanmoInformationCopy1>> positionDetails = gradeEntry.getValue();

            // 创建职位数据的 Map（Position 为大类，包含多个职位）
            Map<String, Object> positionMapResult = new HashMap<>();
            positionMapResult.put("Position", positionType);  // 设置职位类别

            // 计算该职位类别下的所有人员总数
            int peopleCount = positionDetails.values().stream()
                    .mapToInt(List::size)
                    .sum();

            positionMapResult.put("people", peopleCount);  // 设置该职位类别下的人数

            // 创建 positionObject，用于存放该职位类别下的所有职位名称和人员列表
            Map<String, Object> positionObject = new HashMap<>();
            positionObject.put("occupationList", new ArrayList<Map<String, Object>>());  // 初始化职位名称和人员列表

            // 遍历职位名称，并将相关人员数据填充到最终数据列表
            for (Map.Entry<String, List<DanmoInformationCopy1>> positionEntry : positionDetails.entrySet()) {
                String positionName = positionEntry.getKey();  // 职位名称（例如：主席、副书记）
                List<DanmoInformationCopy1> occupationList = positionEntry.getValue();  // 该职位下的人员列表

                // 创建每个职位名称的数据 Map
                Map<String, Object> positionItem = new HashMap<>();
                positionItem.put("occupation", positionName);  // 设置职位名称
                positionItem.put("people", occupationList.size());  // 设置该职位下的人数

                // 填充该职位下的人员信息
                List<Map<String, Object>> occupationDetails = new ArrayList<>();
                for (DanmoInformationCopy1 personalInfo : occupationList) {
                    Map<String, Object> personalInfoMap = new HashMap<>();
                    personalInfoMap.put("personalInfo", personalInfo);  // 将个人信息放入 Map 中
                    occupationDetails.add(personalInfoMap);
                }
                positionItem.put("occupationList", occupationDetails);  // 将人员列表放入职位项

                // 将职位项添加到 positionObject 中
                ((List<Map<String, Object>>) positionObject.get("occupationList")).add(positionItem);
            }

            // 将 positionObject 放入最终的 positionMapResult
            positionMapResult.put("positionObject", positionObject);

            // 将 positionMapResult 添加到最终的数据列表
            dataList.add(positionMapResult);
        }

// 设置最终的列表数据
        danmoProvincesCities.setList(dataList);

// 设置省市信息（从数据中提取）
        String province = danmoProvincesCities.getProvince();

// 根据关联类型获取表名
//        String tableName = determineTable(danmoInformationCopy1.getAssociationType());

// 获取统计数据（人数等）
//        int count = danmoInformationCopy1Mapper.statistics(tableName, danmoInformationCopy1);
        Map<Long, List<DanmoInformationCopy1>> collect = danmoInformations.stream().collect(Collectors.groupingBy(DanmoInformationCopy1::getId));
        danmoProvincesCities.setPeople(collect.size());  // 设置人员总数
// 返回合并后的数据
        return danmoProvincesCities;
    }

    @Autowired
    private DanmoInformationMassMapper danmoInformationMassMapper;

    @Override
    public DanmoProvincesCities selectGreekCouncil(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 获取与之相关的 DanmoInformationMass 信息
        DanmoInformationMass danmoInformationMass = danmoInformationMassMapper.selectDanmoInformationMassByMassId(danmoInformationCopy1.getMassId());

// 创建 DanmoProvincesCities 对象
        DanmoProvincesCities danmoProvincesCities = new DanmoProvincesCities();
        danmoProvincesCities.setObject(danmoInformationMass);

// 创建一个 Map，用来保存按职位（Position）分类后的数据
        Map<String, Map<String, List<DanmoInformationCopy1>>> positionMap = new HashMap<>();

// 遍历所有 DanmoInformationCopy1 数据，按职位类别和职位名称进行分类
        for (DanmoInformationCopy1 information : danmoInformations) {
            String grade = information.getGrade();  // 获取职位类别（如：职位、理事）
            String positionName = information.getPositionName();  // 获取职位名称（如：常务理事、普通理事）

            if (grade != null && positionName != null) {
                // 确保职位类别存在
                positionMap.computeIfAbsent(grade, k -> new HashMap<>());
                Map<String, List<DanmoInformationCopy1>> gradeMap = positionMap.get(grade);

                // 确保职位名称存在
                gradeMap.computeIfAbsent(positionName, k -> new ArrayList<>());

                // 将当前成员信息加入对应职位名称下
                gradeMap.get(positionName).add(information);
            }
        }

// 计算总人数
        int totalPeople = 0;
        for (Map<String, List<DanmoInformationCopy1>> gradeMap : positionMap.values()) {
            for (List<DanmoInformationCopy1> positionList : gradeMap.values()) {
                totalPeople += positionList.size();
            }
        }

// 将职位 Map 转换为目标格式的 List
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Map<String, List<DanmoInformationCopy1>>> gradeEntry : positionMap.entrySet()) {
            String positionType = gradeEntry.getKey();  // 职位类别，如 "职位" 或 "理事"
            Map<String, List<DanmoInformationCopy1>> positionDetails = gradeEntry.getValue();

            // 创建职位类别对应的数据结构
            Map<String, Object> positionMapResult = new HashMap<>();
            positionMapResult.put("Position", positionType);

            // 统计该类别下的总人数
            int positionTypePeopleCount = 0;

            // 遍历该职位类别下的每个职位名称
            List<Map<String, Object>> occupationListResult = new ArrayList<>();
            for (Map.Entry<String, List<DanmoInformationCopy1>> positionEntry : positionDetails.entrySet()) {
                String positionName = positionEntry.getKey();  // 具体职位名称
                List<DanmoInformationCopy1> occupationList = positionEntry.getValue();

                // 创建职位对象
                Map<String, Object> positionObject = new HashMap<>();
                positionObject.put("occupation", positionName);

                // 将该职位下的成员信息（personalInfo）放入 occupationList
                List<Map<String, Object>> personalInfoList = new ArrayList<>();
                for (DanmoInformationCopy1 personalInfo : occupationList) {
                    Map<String, Object> personalInfoMap = new HashMap<>();
                    personalInfoMap.put("personalInfo", personalInfo);  // 将个人信息放入 Map 中
                    personalInfoList.add(personalInfoMap);
                }

                // 添加职位下的成员列表
                positionObject.put("occupationList", personalInfoList);

                // 记录该职位名称的总人数
                positionTypePeopleCount += occupationList.size();

                // 将该职位对象加入职位类别的 Map 中
                occupationListResult.add(positionObject);
            }

            // 设置该职位类别下的总人数
            positionMapResult.put("people", positionTypePeopleCount);

            // 将职位类别的数据加入最终的结果列表
            positionMapResult.put("occupation", occupationListResult);
            result.add(positionMapResult);
        }

// 设置最终结果到 DanmoProvincesCities
        danmoProvincesCities.setList(result);
        danmoProvincesCities.setPeople(totalPeople);  // 设置总人数

// 设置省市信息（假设 DanmoInformationMass 有一个 getProvince() 方法来获取省市）
        danmoProvincesCities.setProvince(danmoInformationMass.getProvince());  // 假设 DanmoInformationMass 有一个 getProvince() 方法来获取省市

// 返回结果
        return danmoProvincesCities;

    }

    @Override
    public DanmoProvincesCities checkClubsList(DanmoInformationCopy1 danmoInformationCopy1) {

// 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 获取 DanmoInformationMass 对象
        DanmoInformationMass danmoInformationMass = danmoInformationMassMapper.selectDanmoInformationMassByMassId(danmoInformationCopy1.getMassId());

// 创建 DanmoProvincesCities 对象，并设置 danmoInformationMass
        DanmoProvincesCities danmoProvincesCities = new DanmoProvincesCities();
        danmoProvincesCities.setObject(danmoInformationMass);

// 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<DanmoInformationCopy1>> groupedData = new TreeMap<>();

// 首先初始化所有字母（A-Z）和 "others" 的空列表
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }
        groupedData.put("others", new ArrayList<>()); // 如果你需要一个 "others" 类别

// 按照拼音首字母分组
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取拼音首字母
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());

            // 如果拼音首字母不在 A-Z 之间，则归为 "others" 类别
            if (pinyinInitial.matches("[A-Z]")) {
                groupedData.computeIfAbsent(pinyinInitial, k -> new ArrayList<>()).add(information);
            } else {
                groupedData.get("others").add(information);
            }
        }

// 将分组结果转换为 List，方便返回
        List<Map<String, List<DanmoInformationCopy1>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformationCopy1>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformationCopy1>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

// 将分组结果设置到 danmoProvincesCities 对象中
        danmoProvincesCities.setList(result);

// 返回结果
        return danmoProvincesCities;

    }

    @Override
    public DanmoProvincesCities<List<Map<String, List<DanmoInformationCopy1>>>> selectCity(DanmoInformationCopy1 danmoInformationCopy1) {

        // 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);
        DanmoProvincesCities<List<Map<String, List<DanmoInformationCopy1>>>> danmoProvincesCities = new DanmoProvincesCities<>();

        // 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<DanmoInformationCopy1>> groupedData = new TreeMap<>();

        // 首先初始化所有字母（A-Z）和 "others" 的空列表
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }

        // 按照拼音首字母分组
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取拼音首字母（不会修改原来的 name 字段）
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());
            danmoProvincesCities.setProvince(information.getAddressCity());

            // 将数据根据拼音首字母分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())
                    .add(information);
        }

        // 将分组结果转换为List形式，方便返回
        List<Map<String, List<DanmoInformationCopy1>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformationCopy1>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformationCopy1>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());

//        int count = danmoInformationCopy1Mapper.statistics(tableName, danmoInformationCopy1);
        Long count = danmoPersonInfoService.statistics(danmoInformationCopy1);

        danmoProvincesCities.setPeople(count.intValue());

        danmoProvincesCities.setList(result);
        // 返回结果
        return danmoProvincesCities;
    }

    @Override
    public DanmoProvincesCities selectCouncilCity(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取所有数据
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 存放数据的 List
        List<Map<String, Object>> dataList = new ArrayList<>();
        DanmoProvincesCities danmoProvincesCities = new DanmoProvincesCities();

// 使用 Map 按职位类别和职位名称分类
        Map<String, Map<String, List<DanmoInformationCopy1>>> positionMap = new HashMap<>();

// 遍历所有 DanmoInformation 对象
        for (DanmoInformationCopy1 information : danmoInformations) {
            String grade = information.getGrade();  // 例如：职位、理事
            String positionName = information.getPositionName();  // 例如：常务理事、普通理事等
            danmoProvincesCities.setProvince(information.getAddressCounty()); // 设置省份

            // 只有 grade 和 positionName 都不为 null 时，才执行逻辑
            if (grade != null && positionName != null) {
                DanmoInformationCopy1 personalInfo = information;  // 个人信息

                // 确保类别（职位、理事）存在
                if (!positionMap.containsKey(grade)) {
                    positionMap.put(grade, new HashMap<>());
                }

                // 获取该类别下职位名称对应的 Map
                Map<String, List<DanmoInformationCopy1>> gradeMap = positionMap.get(grade);

                // 确保职位名称存在
                if (!gradeMap.containsKey(positionName)) {
                    gradeMap.put(positionName, new ArrayList<>());
                }

                // 将个人信息添加到对应职位名称下
                gradeMap.get(positionName).add(personalInfo);
            }
        }

// 将职位 Map 转换为目标格式的 dataList
        for (Map.Entry<String, Map<String, List<DanmoInformationCopy1>>> entry : positionMap.entrySet()) {
            String positionType = entry.getKey();  // "职位" 或 "理事"
            Map<String, List<DanmoInformationCopy1>> positionDetails = entry.getValue();

            // 对于每个职位类型，创建一个新的 Map 用于存储最终的数据
            Map<String, Object> positionMapResult = new HashMap<>();
            positionMapResult.put("Position", positionType);

            // 初始化人数为 0
            int totalPeople = 0;

            // 创建 personalInfo 列表
            List<Map<String, Object>> personalInfoList = new ArrayList<>();

            // 遍历该职位类型下的每个职位名称
            for (Map.Entry<String, List<DanmoInformationCopy1>> positionEntry : positionDetails.entrySet()) {
                String positionName = positionEntry.getKey();  // "常务理事" 等
                List<DanmoInformationCopy1> occupationList = positionEntry.getValue();

                // 创建 positionObject 内容
                Map<String, Object> positionObject = new HashMap<>();
                positionObject.put("occupation", positionName);
                positionObject.put("occupationList", new ArrayList<Map<String, Object>>());

                // 将 occupationList 填充为对应的个人信息
                for (DanmoInformationCopy1 personalInfo : occupationList) {
                    Map<String, Object> personalInfoMap = new HashMap<>();
                    personalInfoMap.put("personalInfo", personalInfo);  // 将个人信息放入 Map 中
                    ((List<Map<String, Object>>) positionObject.get("occupationList")).add(personalInfoMap);
                }

                // 将 positionObject 放入 personalInfoList 中
                personalInfoList.add(positionObject);

                // 累加人数
                totalPeople += occupationList.size();
            }

            // 设置该职位类型下的总人数
            positionMapResult.put("people", totalPeople);
            positionMapResult.put("personalInfo", personalInfoList);  // 将 personalInfo 填充进去

            // 将构造好的 positionMapResult 加入最终数据列表
            dataList.add(positionMapResult);
        }

// 将最终的 dataList 设置到 DanmoProvincesCities 对象中
        danmoProvincesCities.setList(dataList);

// 获取数据表名（根据关联类型）
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());

// 获取统计数据（如人数等）
//        int count = danmoInformationCopy1Mapper.statistics(tableName, danmoInformationCopy1);
        Long count = danmoPersonInfoService.statistics(danmoInformationCopy1);


// 设置总人数
        danmoProvincesCities.setPeople(count.intValue());



// 返回最终的响应
        return danmoProvincesCities;


    }

    @Override
    public DanmoProvincesCities selectProvince(DanmoInformationCopy1 danmoInformationCopy1) {
// 获取所有数据
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 存放数据的 List
        List<Map<String, Object>> dataList = new ArrayList<>();
        DanmoProvincesCities danmoProvincesCities = new DanmoProvincesCities();

// 使用 Map 按职位大类（PositionType）分类
        Map<String, Map<String, Object>> positionMap = new HashMap<>();

// 遍历所有 DanmoInformation 对象
        for (DanmoInformationCopy1 information : danmoInformations) {
            String grade = information.getGrade();  // 职位大类，例如：职位、理事
            String positionName = information.getPositionName();  // 职位名称，例如：常务理事、普通理事
            String province = information.getAddressEntry();  // 省份信息

            // 只有 grade 和 positionName 都不为 null 时，才执行逻辑
            if (grade != null && positionName != null) {
                // 确保职位大类存在
                positionMap.putIfAbsent(grade, new HashMap<>());
                Map<String, Object> positionObject = positionMap.get(grade);

                // 获取该职位大类下的 positionDetails 列表
                List<Map<String, Object>> positionDetails = (List<Map<String, Object>>) positionObject.computeIfAbsent("positionDetails", k -> new ArrayList<>());

                // 查找该职位名称是否已经存在
                Optional<Map<String, Object>> existingPosition = positionDetails.stream()
                        .filter(p -> p.get("PositionName").equals(positionName))
                        .findFirst();

                Map<String, Object> positionDetail;
                if (existingPosition.isPresent()) {
                    // 如果已存在该职位名称，则更新该职位的信息
                    positionDetail = existingPosition.get();
                } else {
                    // 否则创建新的职位对象
                    positionDetail = new HashMap<>();
                    positionDetail.put("PositionName", positionName);
                    positionDetail.put("occupationList", new ArrayList<Map<String, Object>>());
                    positionDetail.put("people", 0);  // 初始化人数为 0
                    positionDetails.add(positionDetail);
                }

                // 添加个人信息
                Map<String, Object> personalInfoMap = new HashMap<>();
                personalInfoMap.put("personalInfo", information);
                ((List<Map<String, Object>>) positionDetail.get("occupationList")).add(personalInfoMap);

                // 更新人数
                positionDetail.put("people", ((List<Map<String, Object>>) positionDetail.get("occupationList")).size());

                // 更新省份信息
                positionObject.putIfAbsent("province", province);
            }
        }

// 构建最终的 dataList 格式
        for (Map.Entry<String, Map<String, Object>> entry : positionMap.entrySet()) {
            String positionType = entry.getKey();
            Map<String, Object> positionObject = entry.getValue();

            // 获取 positionDetails 和省份信息
            List<Map<String, Object>> positionDetails = (List<Map<String, Object>>) positionObject.get("positionDetails");
            String province = (String) positionObject.get("province");

            // 计算该职位大类下的总人数
            int totalPeople = positionDetails.stream()
                    .mapToInt(p -> (int) p.get("people"))
                    .sum();

            // 创建 Map 存储该职位大类的数据
            Map<String, Object> positionTypeMap = new HashMap<>();
            positionTypeMap.put("PositionType", positionType);  // 职位大类
            positionTypeMap.put("province", province);  // 省份
            positionTypeMap.put("people", totalPeople);  // 总人数
            positionTypeMap.put("positionDetails", positionDetails);  // 包含所有职位名称的数据

            // 将该职位大类的最终数据添加到 dataList 中
            dataList.add(positionTypeMap);
        }

// 将最终的数据列表设置到 DanmoProvincesCities 中
        danmoProvincesCities.setList(dataList);

// 获取统计数据（例如总人数等）
        int count = danmoInformations.size();
        danmoProvincesCities.setPeople(count);

// 返回最终结果
        return danmoProvincesCities;

    }

    @Override
    public DanmoProvincesCities<List<Map<String, List<DanmoInformationCopy1>>>> selectProvinceList(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);
        DanmoProvincesCities<List<Map<String, List<DanmoInformationCopy1>>>> danmoProvincesCities = new DanmoProvincesCities<>();

        // 创建一个Map，用来保存拼音首字母分组后的结果
        Map<String, List<DanmoInformationCopy1>> groupedData = new TreeMap<>();

        // 首先初始化所有字母（A-Z）和 "others" 的空列表
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }

        // 按照拼音首字母分组
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取拼音首字母（不会修改原来的 name 字段）
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());
            danmoProvincesCities.setProvince(information.getAddressEntry());

            // 将数据根据拼音首字母分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())
                    .add(information);
        }

        // 将分组结果转换为List形式，方便返回
        List<Map<String, List<DanmoInformationCopy1>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformationCopy1>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformationCopy1>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());

//        int count = danmoInformationCopy1Mapper.statistics(tableName, danmoInformationCopy1);
        Long count = danmoPersonInfoService.statistics(danmoInformationCopy1);

        danmoProvincesCities.setPeople(count.intValue());

        danmoProvincesCities.setList(result);
        // 返回结果
        return danmoProvincesCities;
    }

    @Override
    public List<Map<String, List<DanmoInformationCopy1>>> searchAncientNames(DanmoInformationCopy1 danmoInformationCopy1) {
        // 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 创建一个 TreeMap 用于保存拼音首字母分组后的数据，TreeMap 会自动按字母顺序排列
        Map<String, List<DanmoInformationCopy1>> groupedData = new TreeMap<>();

// 初始化所有字母（A-Z）以及 "others" 作为拼音首字母无法确定的项
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }

// 按照拼音首字母对 DanmoInformationCopy1 进行分组
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取该条目的拼音首字母
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());


            // 根据拼音首字母将数据分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())  // 如果该首字母不存在，初始化一个空列表
                    .add(information);
        }

// 将分组后的结果转换为 List<Map<String, List<DanmoInformationCopy1>>> 格式
        List<Map<String, List<DanmoInformationCopy1>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformationCopy1>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformationCopy1>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

// 返回按拼音首字母分组后的结果
        return result;

    }

    @Override
    public List<Map<String, List<DanmoInformationCopy1>>> CheckCalligraphyEnthusiasts(DanmoInformationCopy1 danmoInformationCopy1) {

        // 获取 DanmoInformation 列表
        List<DanmoInformationCopy1> danmoInformations = selectDanmoInformationCopy1List(danmoInformationCopy1);

// 创建一个 TreeMap 用于保存拼音首字母分组后的数据，TreeMap 会自动按字母顺序排列
        Map<String, List<DanmoInformationCopy1>> groupedData = new TreeMap<>();

// 初始化所有字母（A-Z）以及 "others" 作为拼音首字母无法确定的项
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            groupedData.put(String.valueOf(ch), new ArrayList<>());
        }

// 按照拼音首字母对 DanmoInformationCopy1 进行分组
        for (DanmoInformationCopy1 information : danmoInformations) {
            // 获取该条目的拼音首字母
            String pinyinInitial = GetPinyinInitial.getPinyinInitial(information.getName());


            // 根据拼音首字母将数据分类到 groupedData 中
            groupedData
                    .computeIfAbsent(pinyinInitial, k -> new ArrayList<>())  // 如果该首字母不存在，初始化一个空列表
                    .add(information);
        }

// 将分组后的结果转换为 List<Map<String, List<DanmoInformationCopy1>>> 格式
        List<Map<String, List<DanmoInformationCopy1>>> result = new ArrayList<>();
        for (Map.Entry<String, List<DanmoInformationCopy1>> entry : groupedData.entrySet()) {
            Map<String, List<DanmoInformationCopy1>> group = new HashMap<>();
            group.put(entry.getKey(), entry.getValue());
            result.add(group);
        }

// 返回按拼音首字母分组后的结果
        return result;

    }

    @Override
    public DanmoInformationCopy1 selectDanmoInformationReq(DanmoInformationCopy1 danmoInformationCopy1) {
        DanmoInformationCopy1 danmoInformationCopy1s = new DanmoInformationCopy1();
        // 通过userId 查询person信息
        Long personInfo = danmoPersonInfoService.lambdaQuery()
                .eq(DanmoPersonInfo::getUserId, danmoInformationCopy1.getUserId())
                .select(DanmoPersonInfo::getId)
                .count();
        if(personInfo == 0){
            danmoInformationCopy1s.setIsShow("false");
            return danmoInformationCopy1s;
        }
        // 查询当前协会是否有绑定信息
        List<DanmoPersonPosition> list = danmoPersonPositionService.lambdaQuery()
                .eq(DanmoPersonPosition::getPersonId, danmoInformationCopy1.getUserId())
                .eq(DanmoPersonPosition::getAssociationId, danmoInformationCopy1.getAssociation())
                .eq(DanmoPersonPosition::getAssociationTypeId, danmoInformationCopy1.getAssociationType())
                .select(DanmoPersonPosition::getId)
                .list();
        if (CollUtil.isNotEmpty(list)) {
            danmoInformationCopy1s.setIsShow("true");
        }else {
            danmoInformationCopy1s.setIsShow("false");
        }

        return danmoInformationCopy1s;
    }

    @Override
    public DanmoInformationCopy1 selectUser(DanmoInformationCopy1 danmoInformationCopy1) {
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
        DanmoInformationCopy1 danmoInformationCopy11 = danmoInformationCopy1Mapper.selectUser(danmoInformationCopy1, tableName);
        if (danmoInformationCopy11 != null){
            return danmoInformationCopy11;
        }else {
            DanmoInformationCopy1 danmoInformationCopy12 = new DanmoInformationCopy1();
            DanmoInformationBar danmoInformationBar = danmoInformationCopy12.getDanmoInformationBar();
            if (danmoInformationBar ==null ){
                DanmoInformationBar danmoInformationBar1 = new DanmoInformationBar();
                danmoInformationBar1.setChineseName("");
                danmoInformationBar1.setForeignName("");
                danmoInformationBar1.setNationality("");
                danmoInformationBar1.setNational("");
                danmoInformationBar1.setBirthplace("");
                danmoInformationBar1.setDateBirth("");
                danmoInformationBar1.setGraduateSchool("");
                danmoInformationBar1.setVocational("");
                danmoInformationBar1.setRepresentativeWorks("");
                danmoInformationBar1.setMainAchievements("");
                danmoInformationBar1.setPositions("");
                danmoInformationBar1.setProfile("");
                danmoInformationBar1.setInformationId(0L);
                danmoInformationBar1.setUserId(0L);
                danmoInformationCopy12.setDanmoInformationBar(danmoInformationBar1);
            }
            List<DanmoInformationPhotos> danmoInformationPhotosList = danmoInformationCopy12.getDanmoInformationPhotosList();
            if (danmoInformationPhotosList == null){
                List<DanmoInformationPhotos> danmoInformationPhotosList1 = new ArrayList<>();
                DanmoInformationPhotos danmoInformationPhotos = new DanmoInformationPhotos();
                danmoInformationPhotos.setPhotos("");
                danmoInformationPhotos.setInformationId(0L);
                danmoInformationPhotosList1.add(danmoInformationPhotos);
            }
            danmoInformationCopy12.setDanmoInformationPhotosList(danmoInformationPhotosList);

            List<DanmoCollectShellfish> danmoCollectShellfishList = danmoInformationCopy12.getDanmoCollectShellfishList();
            if (danmoCollectShellfishList == null){
                List<DanmoCollectShellfish> danmoCollectShellfishList1 = new ArrayList<>();
                DanmoCollectShellfish danmoCollectShellfish = new DanmoCollectShellfish();
                danmoCollectShellfish.setTimeAgo("");
                danmoCollectShellfish.setAuthor("");
                danmoCollectShellfish.setCreationDate(new Date());
                danmoCollectShellfish.setWidth(0L);
                danmoCollectShellfish.setHeight(0L);
                danmoCollectShellfish.setType(0L);
                danmoCollectShellfish.setMaterial("");
                danmoCollectShellfish.setPrice(new BigDecimal("0"));
                danmoCollectShellfish.setDescription("");
                danmoCollectShellfish.setInformationId(0L);
                danmoCollectShellfishList1.add(danmoCollectShellfish);
            }
            danmoInformationCopy12.setDanmoCollectShellfishList(danmoCollectShellfishList);

            List<DanmoInformationContent> danmoInformationContentList = danmoInformationCopy12.getDanmoInformationContentList();
            if (danmoInformationContentList == null){
                List<DanmoInformationContent> danmoInformationContentList1 = new ArrayList<>();
                DanmoInformationContent danmoInformationContent = new DanmoInformationContent();
                danmoInformationContent.setParentHeading("");
//                danmoInformationContent.setTimeAgo("");
                danmoInformationContent.setRichText("");
                danmoInformationContent.setAtlas("");
                danmoInformationContent.setSort(0L);
                danmoInformationContentList1.add(danmoInformationContent);
            }
            danmoInformationCopy12.setDanmoInformationContentList(danmoInformationContentList);

            List<DanmoInformationFlagship> danmoInformationFlagshipList = danmoInformationCopy12.getDanmoInformationFlagshipList();
            if (danmoInformationFlagshipList == null){
                List<DanmoInformationFlagship> danmoInformationFlagshipList1 = new ArrayList<>();
                DanmoInformationFlagship danmoInformationFlagship = new DanmoInformationFlagship();
                danmoInformationFlagship.setTimeAgo("");
                danmoInformationFlagship.setShoppingFlagshipId(0L);
                danmoInformationFlagship.setNum(0L);
                danmoInformationFlagshipList1.add(danmoInformationFlagship);
           }
            danmoInformationCopy12.setDanmoInformationFlagshipList(danmoInformationFlagshipList);

            List<DanmoInformationMapTitle> danmoInformationMapTitleList = danmoInformationCopy12.getDanmoInformationMapTitleList();
            if (danmoInformationMapTitleList == null){
                List<DanmoInformationMapTitle> danmoInformationMapTitleList1 = new ArrayList<>();
                DanmoInformationMapTitle danmoInformationMapTitle = new DanmoInformationMapTitle();
                danmoInformationMapTitle.setTitle("");
                danmoInformationMapTitle.setViews(0L);
                danmoInformationMapTitleList1.add(danmoInformationMapTitle);
            }
            danmoInformationCopy12.setDanmoInformationMapTitleList(danmoInformationMapTitleList);

            List<DanmoInformationVideo> danmoInformationVideoList = danmoInformationCopy12.getDanmoInformationVideoList();
            if (danmoInformationVideoList == null){
                List<DanmoInformationVideo> danmoInformationVideoList1 = new ArrayList<>();
                DanmoInformationVideo danmoInformationVideo = new DanmoInformationVideo();
                danmoInformationVideo.setVideo("");
                danmoInformationVideoList1.add(danmoInformationVideo);
            }
            danmoInformationCopy12.setDanmoInformationVideoList(danmoInformationVideoList);

            List<DanmoPersonalPictures> danmoPersonalPicturesList = danmoInformationCopy12.getDanmoPersonalPicturesList();
            if (danmoPersonalPicturesList == null){
                List<DanmoPersonalPictures> danmoPersonalPicturesList1 = new ArrayList<>();
                DanmoPersonalPictures danmoPersonalPictures = new DanmoPersonalPictures();
                danmoPersonalPictures.setPicture("");
                danmoPersonalPicturesList1.add(danmoPersonalPictures);
            }
            danmoInformationCopy12.setDanmoPersonalPicturesList(danmoPersonalPicturesList);

            return danmoInformationCopy12;
        }

    }

    @Override
    public Result addDanmoInformation(DanmoInformationCopy1 danmoInformationCopy1) {

            String tableName = determineTable(danmoInformationCopy1.getAssociationType());
        int id = danmoInformationCopy1Mapper.addDanmoInformation(tableName, danmoInformationCopy1);
        addDanmoInformationCalligrapherPosition(danmoInformationCopy1, Long.valueOf(id));

        return Result.success(danmoInformationCopy1.getName(),"添加成功");

    }

    @Override
    public DanmoInformationCopy1 obtainPersonal(DanmoInformationCopy1 danmoInformationCopy1) {
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
        return danmoInformationCopy1Mapper.selectUserDanmoInformationCopy1(danmoInformationCopy1,tableName);
    }

    @Override
    public Result addFurther(DanmoInformationCopy1 danmoInformationCopy1, Long id) throws UnsupportedEncodingException {

        addDanmoPersonalPictures(danmoInformationCopy1, id);

        addDanmoInformationMapTitle(danmoInformationCopy1, id);

        addDanmoInformationBar(danmoInformationCopy1, id);
        addDanmoInformationContent(danmoInformationCopy1, id);

        return Result.success(danmoInformationCopy1,"添加成功");

    }

    @Override
    public List<DanmoInformationCopy1> selectUserIdList(List<Long> longs) {
        return danmoInformationCopy1Mapper.selectUserIdList(longs);
    }


    /**
     * 艺术家类型统计
     * @param personAddDTO
     */
    public void associationTypeCount(PersonAddDTO personAddDTO,DanmoPersonInfo personInfo){
        // 小团体的统计
        if(CollUtil.isNotEmpty(personAddDTO.getPersonPositionList())){
            // 已经有值，需要判断是否重复绑定小社团
            personAddDTO.getPersonPositionList().forEach(a ->{
                if(a.getAssociationTypeId() != null){
                    // 查询关联关系表
                    Long personPosition = danmoPersonPositionService.lambdaQuery().eq(DanmoPersonPosition::getPersonId, personInfo.getId())
                            .eq(DanmoPersonPosition::getAssociationTypeId, a.getAssociationTypeId()).count();
                    if(personPosition.equals(0L)){
                        DanmoAssociationType danmoAssociationType = iDanmoAssociationTypeService.lambdaQuery().eq(DanmoAssociationType::getId, a.getAssociationTypeId()).one();
                        if(null != danmoAssociationType){
                            iDanmoAssociationTypeService.lambdaUpdate().eq(DanmoAssociationType::getId, danmoAssociationType.getId())
                                    .set(DanmoAssociationType::getNumber, danmoAssociationType.getNumber() + 1).update();
                        }
                    }else {
                        log.info("{}已经绑定艺术家类型{}", personInfo.getId(), a.getMassId());
                    }
                }
            });
        }
    }


    /**
     * 社团统计
     * @param personAddDTO
     */
    public void massCount(PersonAddDTO personAddDTO,DanmoPersonInfo personInfo){
        // 小团体的统计
        if(CollUtil.isNotEmpty(personAddDTO.getPersonPositionList())){
            // 已经有值，需要判断是否重复绑定小社团
            personAddDTO.getPersonPositionList().forEach(a ->{
                if(a.getMassId() != null){
                    // 查询关联关系表
                    DanmoPersonPosition personPosition = danmoPersonPositionService.lambdaQuery().eq(DanmoPersonPosition::getPersonId, personInfo.getId())
                            .eq(DanmoPersonPosition::getMassId, a.getMassId()).one();
                    if(null == personPosition){
                        DanmoInformationMass mass = danmoInformationMassService.lambdaQuery().eq(DanmoInformationMass::getMassId, a.getMassId()).one();
                        if(null != mass){
                            danmoInformationMassService.lambdaUpdate().eq(DanmoInformationMass::getMassId, a.getMassId())
                                    .set(DanmoInformationMass::getNumber, mass.getNumber() + 1).update();
                        }
                    }else {
                        log.info("{}已经绑定小社团{}", personInfo.getId(), a.getMassId());
                    }
                }
            });
        }
    }


    /**
     * 新增person信息
     * @param personAddDTO
     */
    public DanmoPersonInfo addPersonInfo(PersonAddDTO personAddDTO) {
        DanmoPersonInfo personInfo = personMapper.to(personAddDTO);

        // 判断是否存在
        if (StrUtil.isNotEmpty(personAddDTO.getIdCard())) {
            DanmoPersonInfo person = danmoPersonInfoService.lambdaQuery()
                    .eq(DanmoPersonInfo::getIdCard, personAddDTO.getIdCard())
                    .select(DanmoPersonInfo::getId)
                    .one();
            if (person != null) {
                personInfo.setId(person.getId());
            }
        } else {
            // 如果没有身份证号，通过姓名和入会省市区来判断
            List<DanmoPersonInfo> list = danmoPersonInfoService.lambdaQuery()
                    .eq(DanmoPersonInfo::getName, personAddDTO.getName())
                    .select(DanmoPersonInfo::getId)
                    .list();

            if (CollUtil.isNotEmpty(list)) {
                if (CollUtil.isNotEmpty(personAddDTO.getPersonPositionList())) {
                    for (DanmoPersonInfo a : list) {
                        for (PersonPositionDTO b : personAddDTO.getPersonPositionList()) {
                            List<DanmoPersonPosition> personPositions = danmoPersonPositionService.lambdaQuery()
                                    .eq(DanmoPersonPosition::getPersonId, a.getId())
                                    .eq(DanmoPersonPosition::getAddressEntry, b.getAddressEntry())
                                    .eq(DanmoPersonPosition::getAddressCity, b.getAddressCity())
                                    .eq(DanmoPersonPosition::getAddressCounty, b.getAddressCounty())
                                    .list();
                            if (CollUtil.isNotEmpty(personPositions)) {
                                personInfo.setId(a.getId());
                                break; // 找到第一个匹配的 id 后跳出循环
                            }
                        }
                        if (personInfo.getId() != null) {
                            break; // 找到第一个匹配的 id 后跳出循环
                        }
                    }
                }
                if (personInfo.getId() == null) {
                    personInfo.setId(list.get(0).getId()); // 如果没有匹配的省市区，取第一个记录
                }
            }
        }

        // 设置默认值
        if (personInfo.getRealName() == null) {
            personInfo.setRealName(RealName.NO);
        }
        if (personInfo.getConditionStatus() == null) {
            personInfo.setConditionStatus(Condition.review_complete);
        }

        // 保存或更新
        danmoPersonInfoService.saveOrUpdate(personInfo);
        return personInfo;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void add(PersonAddDTO personAddDTO) {
        DanmoPersonInfo personInfo = addPersonInfo(personAddDTO);
        massCount(personAddDTO,personInfo);
        associationTypeCount(personAddDTO,personInfo);
        addDanmoInformationMapTitle(personAddDTO.getDanmoInformationMapTitleList(), personInfo.getId());
        addDanmoInformationBar(personAddDTO.getDanmoInformationBar(), personInfo.getId(),personAddDTO.getDanmoInformationPhotosList(), personAddDTO.getUserId());
        addDanmoInformationContent(personAddDTO.getDanmoInformationContentList(), personInfo.getId());
        addDanmoPersonPosition(personAddDTO.getPersonPositionList(), personInfo.getId());
        addDanmoPersonalPictures(personAddDTO.getDanmoPersonalPicturesList(), personInfo.getId());
    }


    public DanmoInformationCopy1 selectUserDanmoInformationCopy1(DanmoInformationCopy1 danmoInformationCopy1) {
        String tableName = determineTable(danmoInformationCopy1.getAssociationType());
        return danmoInformationCopy1Mapper.selectUserDanmoInformationCopy1(danmoInformationCopy1,tableName);
    }
}
